package com.tobby.camel.camelinaction.chapter3.order;

import org.apache.camel.Header;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PurchaseOrderJSONTest extends CamelTestSupport {

	private static Logger LOG = LoggerFactory.getLogger(PurchaseOrderJSONTest.class);

	@Override
	public RouteBuilder createRouteBuilder() throws Exception {
		return new RouteBuilder() {

			@Override
			public void configure() throws Exception {
				from("jetty://http://localhost:8080/order/service")
						.bean("orderService", "lookup").marshal()
						.json(JsonLibrary.Jackson);
			};
		};
	}

	@Override
	protected JndiRegistry createRegistry() throws Exception {
		JndiRegistry registry = new JndiRegistry();
		registry.bind("orderService", new OrderServiceBean());
		return registry;
	}

	@Test
	public void testJson() {
		String out = template.requestBody("http://localhost:8080/order/service?id-12345",
				null, String.class);
		LOG.info("Response from service : " + out);

		assertNotNull(out);
		assertTrue(out.contains("Camel in Action"));
	}

	public static class OrderServiceBean {
		public PurchaseOrder lookup(@Header("id") String id) {
			LOG.info("Finding purchase order for id " + id);
			// just return a fixed response
			return new PurchaseOrder("Camel in Action", 45.95, 1);
		}
	}

}
